package com.superman.thread;

import lombok.Getter;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * 任务配置
 * Author: superman
 * Date: 2024/5/24 9:49
 */
@Getter
public class TaskConfig implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 任务是否可重复执行
     */
    private boolean repeat;
    /**
     * 重复执行策略，默认废弃后续
     */
    private RepeatStrategyEnum repeatStrategy;
    /**
     * 任务默认超时时长24H
     */
    private long timeout;
    /**
     * 任务默认超时时长24H
     */
    private TimeUnit unit;

    private TaskConfig() {
    }



    public static class Builder {
        /**
         * 任务是否可重复执行
         */
        private boolean repeat;
        /**
         * 重复执行策略，默认废弃后续
         */
        private RepeatStrategyEnum repeatStrategy;
        /**
         * 任务默认超时时长24H
         */
        private long timeout;
        /**
         * 任务默认超时时长24H
         */
        private TimeUnit unit;

        /**
         * 默认配置
         * 1、默认不支持重复执行
         * 2、默认任务重复执行阻塞时的策略：废弃后续
         * 3、默认任务超时时间：24H
         */
        public static TaskConfig defaultConfig() {
            TaskConfig taskConfig = new TaskConfig();
            taskConfig.repeat = false;
            taskConfig.repeatStrategy = RepeatStrategyEnum.WASTE_AFTER;
            taskConfig.timeout = 24;
            taskConfig.unit = TimeUnit.HOURS;
            return taskConfig;
        }

        /**
         * 任务是否可重复执行
         *
         * @param repeat true-可重复执行
         */
        public Builder repeat(boolean repeat) {
            this.repeat = repeat;
            return this;
        }

        /**
         * 任务重复执行阻塞时的策略
         *
         * @param repeat         true-可重复执行
         * @param repeatStrategy 任务重复执行阻塞时的策略枚举
         */
        public Builder repeat(boolean repeat, RepeatStrategyEnum repeatStrategy) {
            this.repeat = repeat;
            this.repeatStrategy = repeatStrategy;
            return this;
        }

        /**
         * 任务超时时长
         */
        public Builder timeout(long timeout, TimeUnit unit) {
            this.timeout = timeout;
            this.unit = unit;
            return this;
        }

        /**
         * 构建任务配置
         */
        public TaskConfig build() {
            TaskConfig taskConfig = defaultConfig();
            taskConfig.repeat = this.repeat;
            if (this.repeat && null != this.repeatStrategy) {
                taskConfig.repeatStrategy = this.repeatStrategy;
            }
            if (null != this.unit) {
                taskConfig.timeout = this.timeout;
                taskConfig.unit = this.unit;
            }
            return taskConfig;
        }

    }

}
